#include "engine.h"
#include "game.h"
#include "render/rendersystem.h"
#include "input/input.h"
#include "3rdparty/Leo/LeoAPI.h"
#include "math/random.h"
#include "entity/scene.h"
#include "script/script.h"
#include "Sound/soundentity.h"
#include "font/font.h"

extern bool kelleo;

game_t::game_t()
{
 	GAME=this;
}

game_t::~game_t()
{
	GAME=0;
}

void game_t::init(HWND render_hwnd,HWND main_hwnd)
{
	rendersystem_t::init(render_hwnd);
	if (main_hwnd)
		inputsystem_t::init(main_hwnd);
	else
		inputsystem_t::init(render_hwnd);
	script_manager_t::init();
	factorymanager_t::init();
	SOUNDMAN=new CSoundManager();
	if (main_hwnd)
		SOUNDMAN->Initialize(main_hwnd, DSSCL_NORMAL);
	else
		SOUNDMAN->Initialize(render_hwnd, DSSCL_NORMAL);

	get_font("textures/fonts/palatino");

	frametimer.start();

	endgame=false;

	scene=NULL;

#ifndef LEO_DESIGNER
	scene_to_load="scenes/startscreen";
#endif
}

void game_t::exit()
{
	if (scene)
	{
		scene->exitrecursive();
		scene->eraserecursive();
	}

	flush_fonts();

	if (SOUNDMAN)
	{
		delete SOUNDMAN;
		SOUNDMAN=0;
	}
	script_manager_t::exit();
	inputsystem_t::exit();
	rendersystem_t::exit();
}

bool game_t::update()
{
	float frametime=0.016666f;
	int updatecount=1;

	if (RSYS->captureisvan)
	{
		frametime=0.033333f;
		updatecount=2;
	}
//	RSYS->flushbuffers();
	if (1 && frametimer.getactseconds()<frametime)
	{
		voltupdate=false;
		return false;
	}

	if (scene_to_load.size()>0)
	{
		if (scene)
		{
			scene->exitrecursive();
			scene->eraserecursive();
		}
		scene=(scene_t*)load_scene_from_file(scene_to_load.c_str());

		ASSERTTXT(scene->isa(scene_t::get_class_typeid()),"csalas");

		if (scene)
			scene->initrecursive();
		else
			ASSERTTXT(0,"valami gyik van");

		scene_to_load.clear();

	}
	voltupdate=true;
//	RSYS->print(700,50,_str("SPEED: %d ms",(int)(frametimer.getactseconds()*1000)));
	frametimer.start();
for (int fak=0; fak<updatecount; ++fak)
{
	INPSYS->update();

	if (INPSYS->keyboard.key_pressed(DIK_R))
	{
		if (scene)
		{
			scene->exitrecursive();
			scene->initrecursive();
		}
	}


	if (scene)
		scene->updaterecursive();

#ifndef LEO_DESIGNER
	if (INPSYS->keyboard.key_pressed(DIK_X))
	{
		endgame=true;
	}
#endif
}
	bool e=endgame;
	endgame=false;

#ifndef LEO_DESIGNER
	if (e)
	{
		scene_to_load="scenes/startscreen";
	}
#endif

	return e;
}

void game_t::render(bool everything)
{
	if ((!voltupdate) && !everything)
		return;
	if (scene)
		scene->renderrecursive(everything);
	RSYS->render();
}

game_t* GAME=NULL;